package algorithm;

public class leetcode_1049 {
    public int lastStoneWeightII(int[] stones) {
        int len=stones.length;
        if(len==1) return stones[0];
        int sum=0;
        for(int i=0;i<len;++i){
            sum+=stones[i];
        }
        int [][] dp=new int[len+1][sum/2+1];
        for(int i=1;i<=len;++i){
            for(int j=1;j<=sum/2;++j){
                if(j>=stones[i-1]) dp[i][j]=Math.max(dp[i-1][j],dp[i-1][j-stones[i-1]]+stones[i-1]);
                else dp[i][j]=dp[i-1][j];
            }
        }
        int max=0;
        for(int i=0;i<=len;++i){
            max=Math.max(max,dp[i][sum/2]);
        }
        return sum-max*2;
    }
}
